package controllers.Account;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import controllers.displayEntites.LoginDisplay;

@ServerEndpoint(value = "/webSocket/{sessionId}", configurator = HttpSessionConfigurator.class)
public class OtherAgainLoginByWebSocket {

	// start(Session session)与onOpen(Session session)只能调用其中一个
	@OnOpen
	public void start(@PathParam("sessionId") String sessionId,
			Session session, EndpointConfig config)

	{
		System.out.println("webSocket start连接成功！ " + session.getId());

		// HttpSession httpSession = (HttpSession)
		// config.getUserProperties().get(
		// HttpSession.class.getName());
		// System.out.println("webSocket get SessionID:" + httpSession.getId());
		// LoginDisplay login = (LoginDisplay)
		// httpSession.getAttribute("login");
		// System.out.println(httpSession + "通過webSocket獲取到的login: " + login);

		HttpSession httpSession = LoginSessionMap.SESSIONID_SESSION
				.get(sessionId);
		LoginDisplay login = (LoginDisplay) httpSession.getAttribute("login");
		System.out.println("通过LoginSessionMap getHttpStssion ID:"
				+ httpSession.getId() + "  Login: " + login + " oldMsg:"
				+ httpSession.getAttribute("orderLoginMsg"));

	}

	/**
	 * 连接成功
	 */
	// @OnOpen
	// public void onOpen(Session session, EndpointConfig config) {
	//
	// System.out.println("webSocket onOpen成功！ " + session.getId());
	// HttpSession httpSession = (HttpSession) config.getUserProperties().get(
	// HttpSession.class.getName());
	// System.out.println("webSocket get SessionID:" + httpSession.getId());
	// LoginDisplay login = (LoginDisplay) httpSession.getAttribute("login");
	// System.out.println(httpSession + "通過webSocket獲取到的login: " + login);
	//
	// }

	@OnMessage
	public void reMessage(HttpServletRequest request, Session session,
			String str)

	{

		try

		{
			// while (true) {
			// System.out.println(request);

			session.getBasicRemote().sendText(str + " who are you");
			// }

		}

		catch (IOException e)

		{

			e.printStackTrace();

		}

	}

	@OnError
	public void error(Session session, Throwable t)

	{

		t.printStackTrace();

	}

	@OnClose
	public void close()

	{

	}
}
